<?php

namespace app\modules\api\controllers;

use Yii;
use yii\web\Controller;
use common\models\Tools;
use common\models\User;
use common\models\UserFriendRequest;
use common\models\UserFriend;
use common\models\Chat;
use common\models\ChatMsg;

/**
 * Default controller for the `api` module
 */
class FriendsController extends Controller
{
    public $enableCsrfValidation = false;
    
    /***
     * 好友搜索
     * url:/api/friends/search
     * 
     */
    public function actionSearch(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        
        $userinfo = Tools::GetSafeParam('userinfo', '', 1);
        
        if(empty($userinfo)){
            $output['success'] = 2;
            $output['msg'] = "用户信息不能为空！";
            Tools::outputjson($output);
        }
        
        if(preg_match("/^1[23456789]{1}\d{9}$/",$userinfo)){
            $model = User::findOne(['mobile'=>$userinfo]);
        }else{
            $model = User::findOne(['username'=>$userinfo]);
        }
        
        if(!empty($model)){
            $output['success'] = 1;
            $output['msg'] = "请求成功！";
            $data['userid'] = $model->id;
            $data['username'] = $model->username;
            $data['headimg'] = $model->headimg;
            $output['data'] = $data;
        }
        else{
            $output['success'] = 2;
            $output['msg'] = "不存在该用户！";
        }
        Tools::outputjson($output);
    }
    
    public function actionAdd(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $friends_userid = Tools::GetSafeParam('userid', '', 1);
        if($friends_userid == ""){
            $output['success'] = 2;
            $output['msg'] = "数据错误！";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $username = Yii::$app->user->identity->username;
        $userhead = Yii::$app->user->identity->headimg;
        
        if($friends_userid == $userid){
            $output['success'] = 2;
            $output['msg'] = "不能添加自己！";
            Tools::outputjson($output);
        }
        
        $friend_model = \common\models\UserFriend::findOne(['userid'=>$userid,'friendid'=>$friends_userid]);
        if(!empty($friend_model)){//已经是好友
            $output['success'] = 2;
            $output['msg'] = "已经是好友了！";
            Tools::outputjson($output);
        }
        
        //已存在的请求，直接返回成功
        $exist = UserFriendRequest::findOne(['user'=>$userid,'to_user'=>$friends_userid]);
        if(!empty($exist)){
            if($exist->deal == 3){
                $output['success'] = 2;
                $output['msg'] = "该用户拒绝添加好友！";
                Tools::outputjson($output);
            }else{
                if($exist->deal == 2){
                    $exist->deal = 0;
                    $exist->addtime = time();
                    $exist->save();
                }
                $output['success'] = 1;
                $output['msg'] = "请求成功！";
                $data['id'] = $exist->id;
                $data['deal'] = $exist->deal;
                $data['userid'] = $userid;
                $data['username'] = $username;
                $data['headimg'] = $userhead;
                $data['touserid'] = $friends_userid;

                $output['data'] = $data;
                Tools::outputjson($output);
            }
            
        }
        
        //新增好友请求
        $model = new UserFriendRequest();
        $model->user = $userid;
        $model->to_user = $friends_userid;
        $model->addtime = time();
        if($model->save()){
            $output['success'] = 1;
            $output['msg'] = "请求成功！";
            $data['id'] = $model->id;
            $data['deal'] = $model->deal;
            $data['userid'] = $userid;
            $data['username'] = $username;
            $data['headimg'] = $userhead;
            $data['touserid'] = $friends_userid;
            
            $output['data'] = $data;
            Tools::outputjson($output);
        }
        else{
            $output['success'] = 0;
            $output['msg'] = "系统错误！";
            Tools::outputjson($output);
        }
    }
    
    public function actionAccept(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $request_id = Tools::GetSafeParam('id', '', 1);
        if(empty($request_id)){
            $output['success'] = 2;
            $output['msg'] = "参数错误！";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $model = UserFriendRequest::findOne(['id'=>$request_id]);
        if($userid != $model->to_user){
            $output['success'] = 2;
            $output['msg'] = "没有权限！";
            Tools::outputjson($output);
        }
        
        $me = User::findOne(['id'=>$model->to_user]);
        $you = User::findOne(['id'=>$model->user]);
        
        $friendModel_1 = new UserFriend();
        $friendModel_1->userid = $model->to_user;
        $friendModel_1->friendid = $model->user;
        $friendModel_1->letter = Tools::getFirstCharters($you->username);
        $friendModel_1->remarks = $you->username;
        $friendModel_1->addtime = time();
        
        $friendModel_2 = new UserFriend();
        $friendModel_2->userid = $model->user;
        $friendModel_2->friendid = $model->to_user;
        $friendModel_2->letter = Tools::getFirstCharters($me->username);
        $friendModel_2->remarks = $me->username;
        $friendModel_2->addtime = time();
        
        $model->deal = 1;
        
        if($friendModel_1->save() && $friendModel_2->save() && $model->save()){
            $output['success'] = 1;
            $output['msg'] = "操作成功！";
            
            $data['user'] = $model->user;
            $data['to_user'] = $model->to_user;
            
            $output['data'] = $data;
            Tools::outputjson($output);
        }
//        else{
//            $output['success'] = 2;
//            $output['msg'] = $model->errors;
//            Tools::outputjson($output);;
//        }
    }
    
    
    public function actionRefuse(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $request_id = Tools::GetSafeParam('id', '', 1);
        if(empty($request_id)){
            $output['success'] = 2;
            $output['msg'] = "参数错误！";
            Tools::outputjson($output);
        }
        $userid = Yii::$app->user->identity->id;
        $model = UserFriendRequest::findOne(['id'=>$request_id]);
        if($userid != $model->to_user){
            $output['success'] = 2;
            $output['msg'] = "没有权限！";
            Tools::outputjson($output);
        }
        
        $model->deal = 2;
        
        if($model->save()){
            $output['success'] = 1;
            $output['msg'] = "操作成功！";
            Tools::outputjson($output);
        }
//        else{
//            $output['success'] = 2;
//            $output['msg'] = $model->errors;
//            Tools::outputjson($output);;
//        }
    }
    
    /***
     * /api/friends/create-chat
     */
    public function actionCreateChat(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        
        $user1 = Tools::GetSafeParam('user1', 0, 0);
        $user2 = Tools::GetSafeParam('user2', 0, 0);
        
        //校验是否是好友
        if(UserFriend::CheckIsFriend($user1,$user2) == false){
            $output['success'] = 2;
            $output['msg'] = "不是好友关系！";
            Tools::outputjson($output);
        }
        
        $model = new Chat();
        $model->user1 = $user1;
        $model->user2 = $user2;
        $model->lasttime = time();
        $model->addtime = time();
        if($model->save()){
            //保存会话id
            UserFriend::UpdateChatid($user1,$user2,$model->id);
            
            
            $friend = User::findOne(['id'=>$user1]);
            
            //自动发送“已经是好友”消息
            $content = "我们已经是好友了，快来聊天吧！";
            $chatModel = new ChatMsg();
            $chatModel->chat_id = $model->id;
            $chatModel->sender = Yii::$app->user->identity->username;
            $chatModel->senderid = Yii::$app->user->identity->id;
            $chatModel->sendee = $friend->username;
            $chatModel->sendeeid = $friend->id;
            $chatModel->content = $content;
            $chatModel->addtime = time();
            if($chatModel->save()){
                $output['success'] = 1;
                $output['msg'] = "操作成功！";
                $output['friend_id'] = $user1;
                $output['friend_head'] = $friend->headimg == "" ? "/img/user/default-head.png" : $friend->headimg;
                $output['friend_name'] = $friend->username;
                $output['chat_id'] = $model->id;
                $output['msg_id'] = $chatModel->id;
                
                $output['content'] = $content;
                Tools::outputjson($output);
            }
        }
    }
    
    /***
     * 保存聊天消息
     * url:/api/friends/newchatmsg
     */
    public function actionNewchatmsg(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        
        $chatid = Tools::GetSafeParam('chatid', 0, 0);
        $senderid = Tools::GetSafeParam('senderid', 0, 0);
        $sendeeid = Tools::GetSafeParam('sendeeid', 0, 0);
        $sender = Tools::GetSafeParam('sender', "", 1);
        $sendee = Tools::GetSafeParam('sendee', "", 1);
        $content = Tools::GetSafeParam('content', "", 1);
        
        $chatModel = new ChatMsg();
        $chatModel->chat_id = $chatid;
        $chatModel->sender = $sender;
        $chatModel->senderid = $senderid;
        $chatModel->sendee = $sendee;
        $chatModel->sendeeid = $sendeeid;
        $chatModel->content = $content;
        $chatModel->addtime = time();
        if($chatModel->save()){
            Chat::updateLastTime($chatid);
            $output['success'] = 1;
            $output['msg'] = "操作成功！";
            $output['msg_id'] = $chatModel->id;
        }
        Tools::outputjson($output);
    }
    
    /***
     * 获取会话历史消息
     * url:/api/friends/get-historymsg
     */
    public function actionGetHistorymsg(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $chatid = Tools::GetSafeParam('chatid', 0, 0);
        $latest_first = Tools::GetSafeParam('latest_first', 0, 0);
        $data = ChatMsg::getHistoryMsg($chatid, $latest_first);
        $output['success'] = 1;
        $output['msg'] = "操作成功！";
        $output['data'] = $data;
        Tools::outputjson($output);
    }
    
    /***
     * 设置消息为已读
     * url:/api/friends/set-read
     */
    public function actionSetRead(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $chatid = Tools::GetSafeParam('chatid', 0, 0);
        $setRead = ChatMsg::setToReaded($chatid, Yii::$app->user->identity->id);
        if($setRead){
            $output['success'] = 1;
            $output['msg'] = "操作成功！";
            Tools::outputjson($output);
        }
    }
    
    /***
     * 获取好友会话
     * url:/api/friends/getchat
     */
    public function actionGetchat(){
        $output = [];
        if (Yii::$app->user->isGuest) {
            $output['success'] = 0;
            $output['msg'] = "未登录，请先登录！";
            Tools::outputjson($output);
            exit;
        }
        $friendid = Tools::GetSafeParam('friendid', 0, 0);
        
        $chatinfo = Chat::getChat($friendid,Yii::$app->user->identity->id);
        
    }
}
